<template>
  <view>
    <view class="wrap">
      <view class="u-avatar-wrap">
        <image class="u-avatar-demo" :src="form.avatar" mode="aspectFill"></image>
      </view>
      <u-button @click="chooseAvatar" type="success">选择头像</u-button>
      <u-form :model="form" ref="uForm" style="margin: 0 20rpx;">
        <u-form-item label-width="145"  label="*邮箱" prop="email"><u-input :disabled="true" v-model="form.email" /></u-form-item>
        <u-form-item label-width="145"  label="*学号" prop="num"><u-input v-model="form.num" /></u-form-item>
        <u-form-item label-width="145"  label="*姓名" prop="name"><u-input v-model="form.name" /></u-form-item>
        <u-form-item label-width="145"  label="*电话" prop="phoneNumber"><u-input v-model="form.phoneNumber" /></u-form-item>
        <u-form-item label-width="145"  label="*昵称" prop="nickname"><u-input v-model="form.nickname" /></u-form-item>
        <u-form-item label-width="145"  label="*性别" prop="sex">
          <u-radio-group v-model="form.sex" @change="radioGroupChange1">
            <u-radio v-for="(item, index) in list1" :key="index" :name="item.value">
              {{ item.name }}
            </u-radio>
          </u-radio-group>
        </u-form-item>
        <view class="u-tips-color">修改为教师角色需得到授权，请联系管理员</view>
        <u-form-item label-width="145"  label="*角色" prop="role">
          <u-radio-group v-model="form.role" @change="radioGroupChange2">
            <u-radio v-for="(item, index) in list2" :key="item.id" :name="item.name">
              {{ item.name }}
            </u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item label-width="220"  label="*介绍"></u-form-item>
        <u-form-item prop="introduction">
          <u-input type="textarea" :height="100" :auto-height="true" :border="true" v-model="form.introduction" />
        </u-form-item>
      </u-form>
      <u-button @click="submit" type="primary">提交</u-button>
      <view class="u-padding-20"></view>
      <u-button @click="changePassword" type="error">修改密码</u-button>
    </view>
  </view>
</template>

<script>
import {getToken, getUserInfo, removeUserInfo, setUserInfo} from "../../common/auth";
import { getUrl } from "../../utils/constants";

export default {
  data() {
    return {
      form: {
        avatar: '',
        email:  "",
        num: '',
        name: '',
        sex: 1,
        phoneNumber: '',
        nickname: '',
        role: '',
        introduction: ''
      },
      rules: {
        num: [
          {
            required: true,
            message: '学号不能为空',
            trigger: 'blur'
          }
        ],
        name: [
          {
            required: true,
            message: '姓名不能为空',
            trigger: 'blur'
          }
        ],
        phoneNumber: [
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // this.$u.test.mobile()就是返回true或者false的
              return this.$u.test.mobile(value);
            },
            required: true,
            message: '电话号码格式不合法',
            trigger: 'blur'
          }
        ],
        nickname: [
          {
            required: true,
            message: '昵称不能为空',
            trigger: 'blur'
          }
        ],
      },
      list1: [{
        name: '男',
        value: 1
      },
        {
          name: '女',
          value: 0
        },
      ],
      list2: [{
        id: 99,
        name: '学生',
      },
        {
          id: 999,
          name: '教师',
        },
      ],
      //图片上传地址
      action: getUrl() + '/api/upload',
      header: {
        "token": getToken()
      },
      email: ''
    };
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  onLoad(){
    this.$u.api.getInfo().then(res => {
      this.form = res.data;
      this.email = this.form.email;
    })
    // 监听从裁剪页发布的事件，获得裁剪结果
    uni.$on('uAvatarCropper', path => {
      // 上传到服务端
      // #ifdef H5
      this.$u.api.uploadBase64Data(path).then(res => {
        this.form.avatar = res.data;
      })
      // #endif
      // #ifndef H5
      uni.uploadFile({
        url: this.action,
        name: "file",
        filePath: path,
        header: this.header,
        success: (res) => {
          this.form.avatar = JSON.parse(res.data).data;
        }
      });
      // #endif
    })
  },
  methods: {
    checkboxChange(obj) {
      this.check = obj.value;
    },
    // 选中任一radio时，由radio-group触发
    radioGroupChange1(e) {
      this.form.sex = e;
    },
    // 选中任一radio时，由radio-group触发
    radioGroupChange2(e) {
      this.form.role = e;
    },
    submit(){
      if (this.isExistEmail){
        this.$u.toast("该邮箱已被注册！");
        return;
      }
      this.$refs.uForm.validate(valid => {
        if (valid) {
          this.$u.api.updateUser(this.form).then(res => {
            if (res.code === 200){
              let user = getUserInfo();
              removeUserInfo();
              this.form.clazzId = user.clazzId;
              this.form.id = user.id;
              setUserInfo(this.form)
              this.$store.commit("SET_CLAZZ_ID",this.form.clazzId)
              this.$store.commit("SET_AVATAR",this.form.avatar)
              this.$store.commit("SET_EMAIL",this.form.email)
              this.$store.commit("SET_NAME",this.form.name)
              this.$store.commit("SET_ID",this.form.id)
              this.$store.commit("SET_NUM",this.form.num)
              this.$store.commit("SET_ROLE",this.form.role)
              this.$u.toast("修改成功！");
            }
          })
        }
      })
    },
    changePassword(){
      this.$u.route('/pages/change_pwd/change_pwd');
    },
    chooseAvatar() {
      // 此为uView的跳转方法，详见"文档-JS"部分，也可以用uni的uni.navigateTo
      this.$u.route({
        // 关于此路径，请见下方"注意事项"
        url: '/pages/u-avatar-cropper/u-avatar-cropper',
        // 内部已设置以下默认参数值，可不传这些参数
        params: {
          // 输出图片宽度，高等于宽，单位px
          destWidth: 300,
          // 裁剪框宽度，高等于宽，单位px
          rectWidth: 200,
          // 输出的图片类型，如果'png'类型发现裁剪的图片太大，改成"jpg"即可
          fileType: 'jpg',
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.wrap {
  padding: 40rpx;
}

.u-avatar-wrap {
  margin-top: 80rpx;
  overflow: hidden;
  margin-bottom: 80rpx;
  text-align: center;
}

.u-avatar-demo {
  width: 150rpx;
  height: 150rpx;
  border-radius: 100rpx;
}
</style>
